import math
import time
from pathlib import Path

from PIL import Image


def list_files_with_pathlib(folder_path):
    try:
        folder = Path(folder_path)
        if not folder.exists():
            print(f"错误：目录 '{folder_path}' 不存在。")
            return []
        if not folder.is_dir():
            print(f"错误：'{folder_path}' 不是一个目录。")
            return []

        # 获取所有文件（不包括子目录）
        files = [file.name for file in folder.iterdir() if file.is_file()]
        return files
    except PermissionError:
        print(f"错误：没有权限访问目录 '{folder_path}'。")
        return []


def merge_images_grid(image_paths, output_path):
    images = [Image.open(img) for img in image_paths]

    # 自动计算网格（例如 2x2）
    n = len(images)

    cols = math.ceil(math.sqrt(n))
    rows = math.ceil(n / cols)

    # 找出最大宽高（统一尺寸可选）
    max_width = max(img.width for img in images)
    max_height = max(img.height for img in images)

    # 创建画布
    total_width = max_width * cols
    total_height = max_height * rows
    merged = Image.new('RGBA', (total_width, total_height))

    for idx, img in enumerate(images):
        if idx >= rows * cols:
            break
        row = idx // cols
        col = idx % cols
        x = col * max_width
        y = row * max_height

        # 居中粘贴（可选）
        x_offset = x + (max_width - img.width) // 2
        y_offset = y + (max_height - img.height) // 2
        merged.paste(img, (x_offset, y_offset), img)

    merged.save(output_path)
    print(f"✅ 网格拼接完成，保存为: {output_path}")


if __name__ == '__main__':
    print('开始')
    timestamp = int(time.time())
    image_1 = []
    folder_path = "D:\\1\\"
    files = list_files_with_pathlib(folder_path)
    for file_1 in files:
        print(file_1)
    #     image_1.append(file_1[0:-8])
    # unique_arr = list(set(image_1))
    # for aa in unique_arr:
    #     cols = 0
    #     rows = 0
    #     image_paths = []
    #     # 根据文件名找到对应的图片组
    #     output_path = "D:\\2\\" + aa + ".png"
    #     files = list_files_with_pathlib(folder_path)
    #     for file_1 in files:
    #         if file_1.startswith(aa):
    #             image_paths.append(folder_path + file_1)
    #             temp_num = int(file_1[-8:-7])
    #             if temp_num > rows:
    #                 rows = temp_num
    #     rows = (rows + 1)
    #     cols = math.ceil(len(image_paths) / rows)
    #     images = [Image.open(img) for img in image_paths]
    #     # 找出最大宽高（统一尺寸可选）
    #     max_width = max(img.width for img in images)
    #     max_height = max(img.height for img in images)
    #     total_width = max_width * cols
    #     total_height = max_height * rows
    #     merged = Image.new('RGBA', (total_width, total_height))
    #     for idx in range(len(image_paths)):
    #         wei = idx // rows
    #         shou = idx % rows
    #         shou = int(shou)
    #         aaa = ""
    #         if wei > 99:
    #             aaa = folder_path + aa + str(shou) + str(wei) + ".png"
    #         elif wei > 9:
    #             aaa = folder_path + aa + str(shou) + "0" + str(wei) + ".png"
    #         elif wei <= 9:
    #             aaa = folder_path + aa + str(shou) + "00" + str(wei) + ".png"
    #         img = Image.open(aaa)
    #         x = cols * max_width
    #         y = rows * max_height
    #         x_offset = max_width * wei
    #         y_offset = max_height * shou
    #         merged.paste(img, (x_offset, y_offset), img)
    #     merged.save(output_path)
    #
    # print(len(unique_arr))
    # print(len(files))

    # aa = "1B28AA62"
    # cols = 0
    # rows = 0
    # image_paths = []
    # # 根据文件名找到对应的图片组
    # folder_path = "C:\\5\\"
    # output_path = "C:\\6\\1.png"
    # files = list_files_with_pathlib(folder_path)
    # for file_1 in files:
    #     if file_1.startswith(aa):
    #         image_paths.append("C:\\5\\" + file_1)
    #         temp_num = int(file_1[-8:-7])
    #         if temp_num > rows:
    #             rows = temp_num
    # rows = (rows + 1)
    # cols = math.ceil(len(image_paths) / rows)
    # images = [Image.open(img) for img in image_paths]
    # # 找出最大宽高（统一尺寸可选）
    # max_width = max(img.width for img in images)
    # max_height = max(img.height for img in images)
    # # 创建画布
    # total_width = max_width * cols
    # total_height = max_height * rows
    # merged = Image.new('RGBA', (total_width, total_height))
    # for idx in range(len(image_paths)):
    #     wei = idx // rows
    #     shou = idx % rows
    #     shou = int(shou)
    #     aaa = ""
    #     if wei > 99:
    #         aaa = folder_path + aa + str(shou) + str(wei) + ".png"
    #     elif wei > 9:
    #         aaa = folder_path + aa + str(shou) + "0" + str(wei) + ".png"
    #     elif wei <= 9:
    #         aaa = folder_path + aa + str(shou) + "00" + str(wei) + ".png"
    #     img = Image.open(aaa)
    #     x = cols * max_width
    #     y = rows * max_height
    #     x_offset = max_width * wei
    #     y_offset = max_height * shou
    #     merged.paste(img, (x_offset, y_offset), img)
    # merged.save(output_path)

    endTime = int(time.time())
    print(str(endTime - timestamp))
    print('结束')
